import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/model/exam_result.dart';
import 'package:kxy_flutter_app/services/exam_service.dart';
import '../../../auth.dart';
import '../../../model/exam.dart';
import '../../../model/exam_question.dart';

class ExamModel with ChangeNotifier {
  ExamService _examSrv;
  int _duration = 0;
  int _index = 0;
  Exam exam;
  ExamResult examResult;
  List<Question> questionList = new List<Question>();

  int get index => _index;
  int get duration => _duration;
  bool get isComplete {
    if (_duration == 0) {
      return true;
    }

    for (var item in questionList) {
      if (item.userAnswer == null || item.userAnswer.isEmpty) {
        return false;
      }
    }
    return true;
  }

  Question get current {
    if (questionList.length == 0) {
      return null;
    }
    return questionList[_index];
  }

  // 1. 开始考试初始化
  Future startExam(Exam exam) async {
    this.exam = exam;
    _index = 0;
    questionList.clear();
    _examSrv = new ExamService(
      examId: exam.id,
      userId: Auth.instance.userId,
    );
    await loadQuestionList();
    notifyListeners();
  }

  Future loadQuestionList() async {
    var examResult = await _examSrv.getQuestionList(courseId: exam.courseId);
    _duration = examResult.first;
    questionList = examResult.second;
  }

  // 2. 提交每次答题
  Future setAnswer(String answer) async {
    var ques = current;

    // 如果已完成答题，不做处理
    if (ques.confirmed == true) return;

    var success = await _examSrv.submitAnswer(ques.quesId, answer);
    if (success == false) {
      Fluttertoast.showToast(msg: '服务器错误：答题失败！');
    } else {
      ques.userAnswer = answer;
      notifyListeners();
    }
  }

  // 3. 交卷
  Future<bool> submitPaper(int remainingTime) async {
    var tuple = await _examSrv.submitPaper(courseId: exam.courseId);
    var isSuccess = tuple.first;
    var grade = tuple.second;

    if (!tuple.first) {
      Fluttertoast.showToast(msg: '服务器出错：交卷失败！');
    }

    examResult = await _examSrv.getExamResult();
    examResult.grade = grade;

    // 设置所有题为完成状态
    questionList.forEach((item) => item.confirmed = true);
    return isSuccess;
  }

  void changeIndex(int index) {
    if (_index >= 0 && _index < questionList.length) {
      _index = index;
      notifyListeners();
    }
  }

  Future collect() async {
    if (current.isCollect) {
      await _examSrv.cancelCollectQuestion(current.quesId);
      current.isCollect = false;
    } else {
      await _examSrv.collectQuestion(current.quesId);
      current.isCollect = true;
    }
    notifyListeners();
  }

  Question getQuesById(String quesId) {
    var ques = questionList.firstWhere((x) => x.quesId == quesId);
    return ques;
  }
}
